import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:typed_data';

import '../../net/httpsClient.dart';

class SmartNetImage extends StatefulWidget {
  final String imageUrl;
  final double? width;
  final double? height;
  final int clipType;
  final double? radius;
  final String errorImg;
  final BoxFit? fit;
  final int maxRetry;

  const SmartNetImage({
    super.key,
    required this.imageUrl,
    this.width,
    this.height,
    this.clipType = 0,
    this.radius,
    this.errorImg = "assets/IM/ic_picture_error.webp",
    this.fit,
    this.maxRetry = 3,
  });

  @override
  State<SmartNetImage> createState() => _SmartNetImageState();
}

class _SmartNetImageState extends State<SmartNetImage> {
  late String _processedUrl;

  @override
  void initState() {
    super.initState();
    _processedUrl = _addTimestamp(widget.imageUrl);
  }

  String _addTimestamp(String url) {
    final uri = Uri.parse(url);
    return uri.replace(queryParameters: {
      ...uri.queryParameters,
      't': DateTime.now().millisecondsSinceEpoch.toString()
    }).toString();
  }

  Widget _buildClipWidget(Widget child) {
    switch (widget.clipType) {
      case 1:
        return ClipOval(child: child);
      case 2:
        return child;
      default:
        return ClipRRect(
          borderRadius: BorderRadius.circular(widget.radius ?? 36.w),
          child: child,
        );
    }
  }

  @override
  Widget build(BuildContext context) {
    return _buildClipWidget(
      FutureBuilder(
        future: Future.sync(() => HttpsClient.dio.get(
                _addTimestamp(widget.imageUrl),
                options: Options(responseType: ResponseType.bytes)))
            .then((response) => response.data as Uint8List),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Image.memory(
              snapshot.data!,
              width: widget.width,
              height: widget.height,
              fit: widget.fit,
            );
          }
          return Image.asset(
            widget.errorImg,
            width: widget.width,
            height: widget.height,
            fit: BoxFit.cover,
          );
        },
      ),
    );
  }
}